﻿using CRM.Models;
using System.Linq;
using CRM.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Identity;
using CRM.Enums;
using CRM.ViewModels.User;

namespace CRM.Controllers.UserManage
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserGroupController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> userManager;

        public UserGroupController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            this.userManager = userManager;
        }

        [HttpGet("[Action]")]
        public async Task<ResultStruct> GetList([FromQuery] string name, [FromQuery] States? state)
        {
            var u = userManager.GetUserAsync(User).Result;
            IQueryable<UserGroup> sqlQuery = _dbContext.UserGroup.Where(i => i.CompanyId == u.CompanyId).Where(i => i.OemId == u.OemId);

            if (state.HasValue)
            {
                sqlQuery = sqlQuery.Where(i => i.State == state);
            }

            if (!string.IsNullOrEmpty(name))
            {
                sqlQuery = sqlQuery.Where(i => i.Name == name);
            }

            var data = await sqlQuery.OrderBy(i => i.State).ThenByDescending(i => i.Id).ToPaginateAsync(Request);
            return Success(data);
        }

        [HttpPost("[Action]")]
        public async Task<ResultStruct> GetInfo(GetDataId RequestData)
        {
            var row = await _dbContext.UserGroup.Where(m => m.Id == RequestData.Id).FirstOrDefaultAsync();
            return row == null ? Error() : Success(data: row);
        }


        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubAddInfo(JObject jsonData)
        {
            Enum.TryParse(jsonData["state"].ToString(), out States state);
            var u = userManager.GetUserAsync(User).Result;
            UserGroup groupModel = new()
            {
                Name =Convert.ToString(jsonData["name"]),
                State = state,
                CompanyId = u.CompanyId,
                OemId = u.OemId,
                Sort = -Helper.GetNowTimeStamp(),
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            await _dbContext.UserGroup.AddAsync(groupModel);
            await _dbContext.SaveChangesAsync();

            return Success();
        }


        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubEditInfo(JObject jsonData)
        {
            Enum.TryParse(jsonData["state"].ToString(), out States state);
            var id = Convert.ToInt32(jsonData["id"]);
            var row = await _dbContext.UserGroup.FindAsync(id);
            if (row == null) return Error(message: "无权操作");
            row.Name = Convert.ToString(jsonData["name"]);
            row.State = state;
            await _dbContext.SaveChangesAsync();
            return Success();
        }

        [HttpPost("[Action]")]
        public async Task<ResultStruct> delInfo(GetDataId RequestData)
        {
            var row = await _dbContext.UserGroup.FindAsync(RequestData.Id);
            if (row == null) return Error(message: "无权操作");
            
             //查找引用当前用户组下用户
            var ret = await _dbContext.Users.Where(m => m.GroupId == RequestData.Id).FirstOrDefaultAsync();
            if (ret != null) return Error(message: "当前用户组下存在用户，禁止删除。");

            _dbContext.UserGroup.Remove(row);
            await _dbContext.SaveChangesAsync();
            return Success();
        }
    }
}
